﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenPop.Mime;
using System.IO;
using Microsoft.Win32;
using System.Xml;

namespace EmailSchedule
{
    public class Helper
    {
        public static bool IsFirstGetEmail = true;
        public static int count = 0;
        public static string sqlConnectString = "";
        public static Queue<MessageInfo> PendingMessageQueue = null;
        public static Queue<MessageInfo> RespondingMessageQueue = null;
        public static List<string> MessageIdList = new List<string>();
        public static string attachFilePath = "";
        public static string getEmailCustomer = "getEmailCustomer";
        public static string sendEmailToQueue = "sendEmailToQueue";
        public static string sendEmailCustomer = "sendEmailCustomer";
        public static string respondEmailFromQueue = "respondEmailFromQueue";
        public static string emailServerAddress = "";
        public static string emailServerPassword = "";
       public static List<string> uidList;
        public static bool IsFlag = true;
        public static string LogPath;
        public static void InitConfig()
        {
            string strConfig = string.Empty;
            try
            {
                uidList = new List<string>();
                PendingMessageQueue = new Queue<MessageInfo>(10000);
                RespondingMessageQueue = new Queue<MessageInfo>(10000);
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software", true).CreateSubKey("PayNet").CreateSubKey("PayPOST");
                strConfig = registryKey.GetValue("CONFIG_FOLDER").ToString();
                strConfig = strConfig + @"\ATGHR.xml";
                XmlDataDocument xmldoc = new XmlDataDocument();
                FileStream fs = new FileStream(strConfig, FileMode.Open, FileAccess.Read);
                xmldoc.Load(fs);
                XmlNodeList prarameters = xmldoc.GetElementsByTagName("Parameter");
                if (prarameters.Count == 0)
                {
                    Helper.IsFlag = false;
                    LogToFile(LogFileType.TRACE, "Quartz Service Error ,Prameter is Wrong !", "Startup");
                    return;
                }
                sqlConnectString = GetParameterValue(prarameters, "QUERY_CONN");
                LogPath = GetParameterValue(prarameters, "LOG_PATH");
                getEmailCustomer = GetParameterValue(prarameters, "GET_EMAIL_CUSTOMER");
                sendEmailToQueue = GetParameterValue(prarameters, "SEND_EMAIL_TO_QUEUE");
                sendEmailCustomer = GetParameterValue(prarameters, "SEND_EMAIL_CUSTOMER");
                respondEmailFromQueue = GetParameterValue(prarameters, "RESPOND_EMAIL_FROM_QUEUE");
                attachFilePath = GetParameterValue(prarameters, "ATTACH_FILE_PATH");
                emailServerAddress = GetParameterValue(prarameters, "EMAIL_SERVER_ADDRESS");
                emailServerPassword = GetParameterValue(prarameters, "EMAIL_SERVER_PASSWORD");
                if (!Helper.IsFlag)
                {
                    LogToFile(LogFileType.TRACE, "Quartz Service Error ,Key or Value do not have", "Startup");
                    return;
                }
                LogToFile(LogFileType.TRACE, "Quartz Service begin,Success !","Startup");
                IsFlag = true;
            }
            catch (Exception ex)
            {
                IsFlag = false;
                LogToFile(LogFileType.EXCEPTION, "Quartz Service error  : "+ex.Message, "Startup");
            }
        }
        public static string GetParameterValue(XmlNodeList xmlNodelist, string Key )
        {
            try
            {
                foreach (XmlNode node in xmlNodelist)
                {
                    if (node.Attributes["Key"].Value == Key)
                    {
                        return node.Attributes["Value"].Value;
                    }
                }
                Helper.IsFlag = false;
                LogToFile(LogFileType.TRACE, "Quartz Service error, Do not have Key : "+Key , "Startup");
                return "";
            }
            catch(Exception ex)
            {
                Helper.IsFlag = false;
                LogToFile(LogFileType.EXCEPTION, "Quartz Service error,Key or Value Name is Wrong :" + ex.Message, "Startup");
                return "";
            }
        }
        public static void LogToFile(LogFileType LogType, string strMessage,string ModuleName)
        {
            try
            {
                string strLogPath = LogPath + @"\" + ModuleName + @"\" + DateTime.Today.ToString("yyyyMMdd");
                if (System.IO.Directory.Exists(strLogPath) == false)
                {
                    System.IO.Directory.CreateDirectory(strLogPath);
                }
                switch (LogType)
                {
                    case LogFileType.TRACE:
                        strLogPath = strLogPath + @"\TRACE.txt";
                        break;

                    case LogFileType.MESSAGE:
                        strLogPath = strLogPath + @"\MESSAGE.txt";
                        break;

                    case LogFileType.EXCEPTION:
                        strLogPath = strLogPath + @"\EXCEPTION.txt";
                        break;

                    default:
                        strLogPath = strLogPath + @"\TRACE.txt";
                        break;
                }
                //string strLogPath = string.Format("{0}\\QuartzDemo_{1}_{2}.txt", LogPath, DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString());
                FileStream file = File.Exists(strLogPath) ? new FileStream(strLogPath, FileMode.Append, FileAccess.Write) : new FileStream(strLogPath, FileMode.CreateNew, FileAccess.Write);
                var sw = new StreamWriter(file);
                sw.WriteLine("{0} : {1}", DateTime.Now, strMessage);
                sw.Close();
                file.Close();
                //GeneralLogger logger = new GeneralLogger();
                //sttrMessage = DateTime.Now.ToString("HH:mm:ss") + " " + sttrMessage;
                //GeneralFormatter formatter = new GeneralFormatter(sttrMessage);
                //string path = string.Empty;
                //path = LogPath + @"\" + DateTime.Today.ToString("yyyyMMdd") + ((string.IsNullOrEmpty(partnerCode)) ? "" : @"\" + partnerCode);
                //if (!Directory.Exists(path))
                //{
                //    Directory.CreateDirectory(path);
                //}
                //switch (LogType)
                //{
                //    case LogFileType.TRACE:
                //        path = path + @"\TRACE.0";
                //        break;

                //    case LogFileType.MESSAGE:
                //        path = path + @"\MESSAGE.0";
                //        break;

                //    case LogFileType.EXCEPTION:
                //        path = path + @"\EXCEPTION.0";
                //        break;

                //    default:
                //        path = path + @"\TRACE.0";
                //        break;
                //}
                //logger.Write(formatter, path);
            }
            catch { }
        }
    }
    public enum LogFileType
    {
        TRACE = 1,
        MESSAGE = 2,
        EXCEPTION = 3,
    }

}
